package ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.presentation.controller.admin.users;

import java.util.ArrayList;
import java.util.List;

import javax.faces.context.FacesContext;
import javax.faces.context.Flash;

import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.Device;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.persistence.model.SimpleUser;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.presentation.controller.admin.devices.DeviceBean;
import ar.edu.utn.frsf.proyectofinal.sistemadecontrolmodbus.service.SystemService;

public class UserBean {
	
	private SystemService service;
	private SimpleUser user;
	private List<DeviceBean> devices;
	
	public UserBean(SimpleUser user, SystemService service) {
		this.setUser(user);
		this.setService(service);
	}

	public SystemService getService() {
		return service;
	}

	public void setService(SystemService service) {
		this.service = service;
	}

	public SimpleUser getUser() {
		return user;
	}

	public void setUser(SimpleUser user) {
		this.user = user;
	}

	public String getName() {
		return user.getUserName();
	}

	public void setName(String name) {
		user.setUserName(name);
	}

	public String getPass() {
		return user.getPassword();
	}

	public void setPass(String pass) {
		user.setPassword(pass);
	}

	public void edit(){
		Flash flash = FacesContext.getCurrentInstance().getExternalContext().getFlash();
		flash.put("selectedUser", this);
	}
	
	public void delete(){
		service.deleteUser(user);
	}

	public List<DeviceBean> getUserDevices(){
		List<DeviceBean> ret = DeviceBean.wrap(service.getSysDevices(), service);
	    System.out.println("Creando lista dispositivos del usuario");
		for (DeviceBean deviceBean : ret) {
			boolean contain = false;
			for (Device device : user.getDevices()) {
				if(device.getID().equals(deviceBean.getDevice().getID())){
					contain = true;
					break;
				}
			}
			
			deviceBean.setSelected(contain);
			
		}
		devices = ret;
		return ret;				
	}
	
	public void saveChanges(){
		List<Device> userDevs = new ArrayList<Device>();
		for (DeviceBean device : devices) {
			if(device.getSelected())
				userDevs.add(device.getDevice());
		}
		user.setDevices(userDevs);
		service.saveUser(user);
	}
	
	public static List<UserBean> wrap(List<SimpleUser> users, SystemService service) {
		List<UserBean> ret = new ArrayList<UserBean>();

		for (SimpleUser user : users) {
			ret.add(new UserBean(user,service));
		}
		return ret;
	}
}
